package com.hbpu.usercenter.controller;

import com.hbpu.usercenter.common.BaseResponse;
import com.hbpu.usercenter.common.ErrorCode;
import com.hbpu.usercenter.common.ResultUtils;
import com.hbpu.usercenter.dto.UserDTO;
import com.hbpu.usercenter.exception.BusinessException;
import com.hbpu.usercenter.pojo.User;
import com.hbpu.usercenter.request.UserLoginRequest;
import com.hbpu.usercenter.request.UserRegisterRequest;
import com.hbpu.usercenter.vo.LoginUserVO;
import com.hbpu.usercenter.vo.UserLoginOutVO;
import com.hbpu.usercenter.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 负责前端请求的控制层
 *
 * @author 马可
 */
@Tag(name = "负责前端请求的控制层", description = "负责前端请求的控制层")
@RestController
@RequestMapping("/user")
//@CrossOrigin(origins = "http://192.168.1.192:4173", allowCredentials = "true")
@Slf4j
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 用户注册
     *
     * @param userRegisterRequest 用户注册参数所对应的实体类
     * @return 注册成功返回该用户id，否则返回null
     *
     */
    @Operation(summary = "用户注册", description = "用户注册")
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long result = userService.registerUser(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest 用户的登录参数所对应的实体类
     * @param request          用户请求
     * @return 登录成功返回User对象，否则返回null
     */
    @Operation(summary = "用户登录", description = "用户登录")
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LoginUserVO user = userService.loginUser(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户注销
     *
     * @param request 用户请求
     * @return 注销成功返回UserLoginOutResponse对象
     */
    @Operation(summary = "用户注销", description = "用户注销")
    @PostMapping("/outLogin")
    public BaseResponse<UserLoginOutVO> loginOut(HttpServletRequest request) {
        UserLoginOutVO result = userService.loginOut(request);
        return ResultUtils.success(result);
    }

    /**
     * 根据用户名查找用户，模糊查询
     *
     * @param username 用户名
     * @param request  用户请求
     * @return 查询到返回User类型的List集合，否则返回null
     */
    @Parameter(name = "username", description = "用户名", in = ParameterIn.PATH, required = true)
    @Operation(summary = "根据用户名查找用户，模糊查询", description = "根据用户名查找用户，模糊查询")
    @GetMapping("/select/{username}")
    public BaseResponse<List<UserDTO>> selectUsers(@PathVariable String username, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "缺少管理员权限");
        }
        if (StringUtils.isEmpty(username) || request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<UserDTO> list = userService.selectUsersByUsername(username);
        return ResultUtils.success(list);
    }

    /**
     * 查询所有用户
     *
     * @param request 用户请求
     * @return 返回用户的List集合
     */
    @Operation(summary = "查询所有用户", description = "查询所有用户")
    @GetMapping("/selectUsers")
    public BaseResponse<List<UserDTO>> selectUsers(HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "缺少管理员权限");
        }
        List<UserDTO> list = userService.selectAllUsers();
        return ResultUtils.success(list);
    }

    /**
     * 根据标签查询用户
     *
     * @param tagNames 标签名
     * @param request  用户请求
     * @return 用户列表
     */
    @Parameter(name = "tagNames", description = "标签名", in = ParameterIn.QUERY, required = true)
    @Operation(summary = "根据标签查询用户", description = "根据标签查询用户")
    @GetMapping("/select/tags")
    public BaseResponse<List<UserDTO>> selectUsersByTags(@RequestParam List<String> tagNames, HttpServletRequest request) {
        if (!userService.isLogin(request)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if (tagNames.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<UserDTO> users = userService.selectByTags(tagNames);
        return ResultUtils.success(users);
    }

    /**
     * 根据用户id删除用户
     *
     * @param id      用户id
     * @param request 用户请求
     * @return 删除成功返回true，否则返回false
     */
    @Parameter(name = "id", description = "用户id", in = ParameterIn.PATH, required = true)
    @Operation(summary = "根据用户id删除用户", description = "根据用户id删除用户")
    @DeleteMapping("/delete/{id}")
    public BaseResponse<Boolean> deleteUser(@PathVariable long id, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "缺少管理员权限");
        }
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Boolean result = userService.deleteUserById(id);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户的信息
     *
     * @param request 用户请求
     * @return 返回脱敏的登录对象
     */
    @Operation(summary = "获取当前登录用户的信息", description = "获取当前登录用户的信息")
    @GetMapping("/current")
    public BaseResponse<UserDTO> getCurrentUser(HttpServletRequest request) {
        UserDTO user = userService.getCurrentUser(request);
        return ResultUtils.success(user);
    }

    /**
     * 判断当前用户是否登录
     * @param request 用户请求
     * @return 已登录返回true，否则返回false
     */
    @Operation(summary = "判断当前用户是否登录", description = "判断当前用户是否登录")
    @GetMapping("/islogin")
    public BaseResponse<Boolean> isLogin(HttpServletRequest request) {
        boolean loginState = userService.isLogin(request);
        if (loginState) {
            return ResultUtils.success(true);
        } else {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
    }

    /**
     * 修改用户信息
     * @param user 由前端传输的要修改的用户信息的包装类
     * @param request 用户请求
     * @return 修改成功返回true，否则返回错误信息
     */
    @Operation(summary = "修改用户信息", description = "修改用户信息")
    @PostMapping("/update")
    public BaseResponse<Boolean> userUpdate(@RequestBody User user,  HttpServletRequest request) {
        if (!userService.isLogin(request)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if (user ==  null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int i = userService.updateUser(user, request);
        if (i > 0) {
            return ResultUtils.success(true);
        } else {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
    }

    /**
     * 根据用户标签推荐用户
     *
     * @param current 当前页码
     * @param size    每页显示的数据量
     * @param request 用户请求
     * @return 查询到的用户列表
     */
    @Operation(summary = "根据用户标签推荐用户", description = "根据用户标签推荐用户")
    @GetMapping("/recommend")
    public BaseResponse<List<UserDTO>> userRecommend(long current, long size, HttpServletRequest request) {
        List<UserDTO> users = userService.recommendUsers(current, size, request);
        if (users.isEmpty()) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return ResultUtils.success(users);
    }
}